﻿using HAF.LogUtility;
using HAF.LogUtility.Assistantor;
using HAF.OfficeEx;
using MediaBusiness.Dto;
using MediaBusiness.Utils;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace MediaBusiness
{
    public partial class FrmMain : Form
    {
        public FrmMain()
        {
            InitializeComponent();
        }

        private void FrmMain_Load(object sender, EventArgs e)
        {
            dtpBegin.Text = DateTime.Now.AddDays(-7).ToString();
            dtpEnd.Text = DateTime.Now.ToString();

            contentCfg = RefreshPluginConfig<List<ContentProvider>>("ContentProvider.json");
        }

        private void btnExit_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        //源数据集
        List<MediaHeadsDto> mediaHeadslst = new List<MediaHeadsDto>();
        //去重后数据集
        List<MediaHeadsDto> cleanlst = new List<MediaHeadsDto>();
        //CP统计集
        List<MediaSet> mediaSets = new List<MediaSet>();
        //配置集
        List<ContentProvider> contentCfg = new List<ContentProvider>();

        private void btnSearch_Click(object sender, EventArgs e)
        {
            GetDatas();
        }

        private void btnClean_Click(object sender, EventArgs e)
        {
            CleanDatas();
        }

        private void btnCount_Click(object sender, EventArgs e)
        {
            //数据统计
            GetDatas();
            CleanDatas();
            CountDatas();
        }

        private void btnExport_Click(object sender, EventArgs e)
        {
            var objsExport = mediaSets.Select(p => new { CP编号 = p.CSPID, CP名称 = p.CSPName, 统计周期 = p.WeekTime, 送审数量 = p.DataCount, 未过审数 = p.AuditCount, 备注 = p.Description }).ToList();
            var datas = ExcelEx.DownloadExcel(objsExport);
            string outFileName = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, string.Format("CP内容授权有效期对比统计{0}-{1}.xlsx", dtpBegin.Value.ToString("MMdd"), dtpEnd.Value.AddDays(-1).ToString("MMdd")));
            using (FileStream fs = new FileStream(outFileName, FileMode.Create, FileAccess.Write, FileShare.ReadWrite))
            {
                fs.Write(datas, 0, datas.Length);
            }
            MessageBox.Show("导出成功");
        }

        private void GetDatas()
        {
            mediaHeadslst.Clear();
            //提取两个数据源数据用于统计
            string connStr = @"server=172.25.8.33;User Id=audit;password=WedoIptv@2017!;Persist Security Info=True;Character set=utf8;database=was;SslMode=none";
            SugarDbContext.Init(connStr);
            List<MediaHeadsDto> lst33 = DataAssistantor.Instance.GetMediaMetainfo(dtpBegin.Text, dtpEnd.Text);
            if (lst33 != null)
            {
                mediaHeadslst.AddRange(lst33);
            }

            connStr = @"server=172.25.8.22;User Id=audit;password=WedoIptv@2017!;Persist Security Info=True;Character set=utf8;database=was;SslMode=none";
            SugarDbContext.Init(connStr);
            List<MediaHeadsDto> lst22 = DataAssistantor.Instance.GetMediaMetainfo(dtpBegin.Text, dtpEnd.Text);
            if (lst22 != null)
            {
                mediaHeadslst.AddRange(lst22);
            }

            dgvResult.DataSource = mediaHeadslst;
            sLabCount.Text = string.Format("共[{0}]条剧头数据", mediaHeadslst.Count);
        }

        private void CleanDatas()
        {
            //去重
            cleanlst.Clear();
            //p => p.CSPID,
            var groups = mediaHeadslst.GroupBy(p => p.MediaCode).Select(g => g.First());
            foreach (var group in groups)
            {
                cleanlst.Add(group);
            }
            //cleanlst.OrderBy(t => t.CSPID);
            cleanlst.Sort((MediaHeadsDto t1, MediaHeadsDto t2) => t1.CSPID.CompareTo(t2.CSPID));

            dgvResult.DataSource = cleanlst;
            sLabCount.Text = string.Format("共[{0}]条剧头数据", cleanlst.Count);
        }

        private void CountDatas()
        {
            mediaSets.Clear();
            //按CSPID统计总数、未通过数量
            var groupLst = cleanlst.GroupBy(p => p.CSPID);
            foreach (var group in groupLst)
            {
                var tmpCfg = contentCfg.Find(t => t.CSPID == group.Key && t.BEnable);
                if (tmpCfg != null)
                {
                    MediaSet media = new MediaSet();
                    media.CSPID = group.Key;
                    media.CSPName = tmpCfg.CSPName;
                    media.WeekTime = string.Format("{0}-{1}", dtpBegin.Value.ToString("MM月dd日"), dtpEnd.Value.AddDays(-1).ToString("MM月dd日"));
                    media.DataCount = group.Count();
                    mediaSets.Add(media);
                    LogHelper.WriteDebugLog("当前CSPID [{0}] 共有 {1} 条剧头数据送审", group.Key, group.Count());
                }
                else
                {
                    LogHelper.WriteWarningLog("当前CSPID[{0}]不可用", group.Key);
                }
            }
            List<string> lst = new List<string>();
            //lst = cleanlst.Select(p=>p.AuditStat)
            var tmpLst = cleanlst.Select(p => new { p.CSPID, p.AuditStat }).ToList();
            foreach (var item in tmpLst)
            {
                //item.CSPID
            }

            var gLst = cleanlst.GroupBy(p => new { p.CSPID, p.AuditStat });
            foreach (var grp in gLst)
            {
                List<string> unAudits = new List<string>();
                string cspid = "";
                foreach (var item in grp)
                {
                    cspid = item.CSPID;
                    if (item.AuditStat == 0)
                    {
                        unAudits.Add(item.MediaName);
                    }
                }
                if (unAudits.Count > 0)
                {
                    var m = mediaSets.Find(t => t.CSPID == cspid);
                    m.AuditCount = unAudits.Count;
                    m.Description = string.Join(",", unAudits.ToArray());
                }

                LogHelper.WriteDebugLog("分组 [{0}] 共有 {1} 条剧头数据", grp.Key, grp.Count());
            }

            //var gLst1 = cleanlst.GroupBy(p => new { p.CSPID, p.AuditStat }, p=>p.CSPID, (key, names) => new { key.CSPID, key.AuditStat });
            //foreach (var item in gLst1)
            //{
            //    LogHelper.WriteDebugLog("分组 [{0}] 共有 {1} 条剧头数据", item.CSPID, item.AuditStat);
            //}
            //sLabCount.Text = string.Format("共[{0}]条数据", gLst.Count()); ;

            dgvResult.DataSource = mediaSets;
            //LogHelper.WriteDebugLog("共有 [{0}] 条数据", mediaSets.Count);
            sLabCount.Text = string.Format("共[{0}]条统计数据", mediaSets.Count);
        }

        /// <summary>
        /// 刷新插件配置
        /// </summary>
        /// <typeparam name="T">配置对象类型</typeparam>
        /// <param name="configName">配置文件名称</param>
        /// <returns></returns>
        protected T RefreshPluginConfig<T>(string configName)
        {
            //获取本地配置文件 每次执行的时候读取，实现热配置
            string loadConfigPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Config", configName);
            if (File.Exists(loadConfigPath))
            {
                T _runConfig = JsonAssistant.FromFile<T>(loadConfigPath);
                if (_runConfig == null)
                {
                    //给请求方应答
                    LogHelper.WriteErrorLog("金沙引擎：工作项外部配置文件加载失败，文件解析失败！");
                    return default(T);
                }
                return _runConfig;
            }
            LogHelper.WriteErrorLog("金沙引擎：工作项外部配置文件加载失败，文件不存在！");
            return default(T);
        }
    }
}
